package com.chengxiaoxiao.filter;

import com.chengxiaoxiao.constant.Constants;
import com.chengxiaoxiao.domain.Users;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        String url = request.getRequestURI();
        HttpSession session = request.getSession(true);

        Users obj = (Users) session.getAttribute(Constants.SESSION_USER_MODEL);

        //用户的请求url为登录或注册页面则视为正常访问
        if( url.contains("png")||url.contains("ClientServlet")||url.endsWith("VaildCode")||url.endsWith("login.jsp") || url.endsWith("js") || url.endsWith("css")|| url.endsWith("gif")|| url.endsWith("jpg")){
            chain.doFilter(request, response);
            return;
        }
        //如果session为空，则说明用户没有登录，将当前网页重定向到登录页面
        if(null == obj){
            System.out.println(url);
            //request.getRequestDispatcher("login.html").forward(request, response);
            response.sendRedirect("login.jsp");
            System.out.println("1");
            chain.doFilter(request, response);
            return;
        }else{
            System.out.println("session is not null");
            chain.doFilter(request, response);
            return;

        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
